import os
import json

class LanguageManager:
    """语言管理器，负责加载和应用语言文件"""
    def __init__(self, lang_dir):
        self.lang_dir = lang_dir
        self.current_language = None
        self.current_dict = {}
        self.default_dict = {
            "app_title": "WSCatcher v3.0",
            "menu": {
                "file": "File",
                "run": "Run",
                "plugins": "Plugins",
                "open_webpage": "打开网页 (Ctrl+O)",
                "save": "保存 (Ctrl+S)",
                "run_html": "运行 (Ctrl+R)",
                "plugin_options": "插件选项",
                "language": "语言 ({current})"
            },
            "status_bar": {
                "ready": "就绪",
                "loading": "正在加载网页...",
                "saving": "正在保存文件...",
                "running": "正在运行...",
                "highlighting": "正在高亮语法..."
            },
            "messages": {
                "load_failed": "加载失败",
                "save_failed": "保存失败",
                "run_failed": "运行失败",
                "save_success": "保存成功",
                "save_success_message": "文件已保存到: {path}",
                "plugin_enabled": "插件已启用",
                "plugin_disabled": "插件已禁用",
                "enable_plugin_failed": "启用插件失败",
                "disable_plugin_failed": "禁用插件失败",
                "select_language": "请选择一种语言",
                "language_already_selected": "{language} 已经是当前启用的语言",
                "restart_required": "需要重启",
                "restart_message": "设置已更改。重启应用程序以应用更改。是否立即重启？",
                "plugin_state_changed": "插件配置已更改。重启应用程序以应用更改。是否立即重启？",
                "language_changed": "语言设置已更改。重启应用程序以应用更改。是否立即重启？"
            },
            "dialogs": {
                "plugin_manager": "插件管理",
                "language_manager": "语言选择",
                "enable_plugin": "启用插件",
                "disable_plugin": "禁用插件",
                "refresh_list": "刷新列表",
                "close": "关闭",
                "select": "选择"
            }
        }
    
    def load_language(self, language_file):
        """加载指定的语言文件"""
        if not language_file:
            self.current_language = None
            self.current_dict = {}
            return
        
        lang_path = os.path.join(self.lang_dir, language_file)
        try:
            with open(lang_path, 'r', encoding='utf-8') as f:
                self.current_dict = json.load(f)
            self.current_language = language_file
            print(f"已加载语言: {language_file}")
        except Exception as e:
            print(f"加载语言文件失败: {str(e)}")
            self.current_dict = {}
    
    def get_text(self, key_path, default=None):
        """获取本地化文本"""
        # 先尝试从当前语言字典获取
        value = self._get_nested_value(self.current_dict, key_path)
        if value is not None:
            return value
        
        # 再尝试从默认语言字典获取
        value = self._get_nested_value(self.default_dict, key_path)
        if value is not None:
            return value
        
        # 如果都没有，返回默认值或键路径
        return default or key_path
    
    def _get_nested_value(self, dictionary, key_path):
        """获取嵌套字典中的值"""
        keys = key_path.split('.')
        current = dictionary
        for key in keys:
            if key not in current:
                return None
            current = current[key]
        return current
